<script setup>
import { ref, computed, onMounted, watchEffect } from 'vue';
import { useStore } from 'vuex';
import { ElDialog, ElMessageBox } from 'element-plus';
import socket from '../../socket';

const store = useStore();
 
//开发平台 编程环境 编程语言 toolchain 范例代码 项目位置
// 1.传镜像名 范例代码 新
// 2.传仓库地址 解析。ini 获得里面的env_image 老

const projectName = ref('');
const projectBoard = ref('');
const projectFramework = ref(store.state.selectFramework);
const programLanguage = ref('');
const projectImage = ref(''); 
const projectExamplecode = ref('https://gitee.com/SuperIDE/examplecode.git');
const useDefaultLocation = ref(true);
const isProjectNameValid = ref(null);
const projectLocation = ref('');

const showDialog = ref(false); // 控制弹窗显示隐藏
const loadingInstance = ref(null); // 引入 loading 实例

onMounted(() => {
  // 调用获取数据的函数
  fetchData();
});

// 异步获取数据的函数
async function fetchData() {
  // 获取项目列表
  await store.dispatch('asyncFetchBoardsData');
  await store.dispatch('asyncSetProjectsDir');
  await store.dispatch('asyncFetchRecentProjectsList');
}

// 项目默认位置
const projectsDir = computed(() => {
  return store.state.ProjectsDir;
});

// 在计算属性 projectsDir 变化时更新 projectLocation
watchEffect(() => {
  projectLocation.value = projectsDir.value;
});

// 新增的计算属性，用于检查项目名称是否为URL
const isProjectNameUrl = computed(() => {
  const urlPattern = new RegExp('^(https?://)?' + // 协议
    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // 域名
    '((\\d{1,3}\\.){3}\\d{1,3}))' + // 或 IP (v4) 地址
    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // 端口和路径
    '(\\?[;&a-z\\d%_.~+=-]*)?' + // 查询字符串
    '(\\#[-a-z\\d_]*)?$', 'i'); // 锚点
  return urlPattern.test(projectName.value);
});

// 检查项目名称是否合法
const checkProjectName = computed(() => {
  // 如果项目名称为空并且isProjectNameValid.value为null，返回 null，初始状态
  if (!projectName.value && isProjectNameValid.value === null) {
    return isProjectNameValid.value = null;
  } else if (!projectName.value || recentProjectsNames.value.includes(projectName.value)) {
    // 如果项目名称为空或者与最近的项目重名，返回 false
    return isProjectNameValid.value = false;
  } else if (projectName.value && !recentProjectsNames.value.includes(projectName.value)) {
    // 否则返回 true
    return isProjectNameValid.value = true;
  }
});

// 假设 recentProjects 是一个数组，存储了最近的项目名称
const recentProjectsNames = computed(() => {
  return store.state.recentProjectslist.map(project => project.name);
});

// 创建计算属性来存储所选开发平台的对象
const selectedBoard = computed(() => {
  return store.state.boardData.find(item => item.name === projectBoard.value) || {};
});

function clickChangeTxt() {
  useDefaultLocation.value = !useDefaultLocation.value;
  changeDefaultLocation();
}

// 根据 useDefaultLocation 的值改变 projectLocation 的值
function changeDefaultLocation() {
  const res = useDefaultLocation.value;
  if (!res) {
    projectLocation.value = '';
  } else {
    projectLocation.value = store.state.ProjectsDir;
  }
}

function addNewProject(newProjectPath) {
  store.commit('add_Recent_Project', newProjectPath);
}

// 提交表单
function handleSubmit() {
    // 显示加载提示
    loadingInstance.value = ElLoading.service({
    lock: true,
    text: '项目创建中...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  if (isProjectNameUrl.value) {
    showDialog.value = true; // 显示弹窗

    socket.emit('clone', [projectName.value, projectLocation.value]);
    socket.on('clone', (res) => {
      showDialog.value = false; // 隐藏弹窗
       // 隐藏加载提示
    loadingInstance.value.close();

      if (res.error) {
        console.error(res.error);
      } else {
        const newProjectPath = projectLocation.value + '/' + res;
        socket.emit('is_file', newProjectPath + '/' + 'platformio.ini');
        socket.on('is_file', (res) => {
          if (res) {
            addNewProject(newProjectPath);
            socket.emit('save_state', { storage: store.state.storage });
            socket.on('save_state', (res) => {
              if (res) {
                fetchData();
              }
            });
            ElMessageBox.alert('项目已创建成功！！！', '提示', {
              confirmButtonText: '确定',
              customClass: 'my-custom-message-box', // 自定义类名
              callback: () => {
                location.reload();
              }
            });
          }
        });
      }
    });
  } else {
    showDialog.value = true; // 显示弹窗

    // 如果项目名称不合法，提示用户
    if (!isProjectNameValid.value) {
      showDialog.value = false; // 隐藏弹窗
      ElMessageBox.alert('请输入合法的项目名称', '错误', {
        confirmButtonText: '确定',
        customClass: 'my-custom-message-box', // 自定义类名
      });
      return;
    }
    // 如果没有选择开发平台，提示用户
    if (!projectBoard.value) {
      showDialog.value = false; // 隐藏弹窗
      ElMessageBox.alert('请选择开发平台', '错误', {
        confirmButtonText: '确定',
        customClass: 'my-custom-message-box', // 自定义类名
      });
      return;
    }
    // 如果没有选择编程框架，提示用户
    if (!projectFramework.value) {
      showDialog.value = false; // 隐藏弹窗
      ElMessageBox.alert('请选择编程框架', '错误', {
        confirmButtonText: '确定',
        customClass: 'my-custom-message-box', // 自定义类名
      });
      return;
    }

    if (!programLanguage.value) {
      showDialog.value = false; // 隐藏弹窗
      ElMessageBox.alert('请输入编程语言', '错误', {
        confirmButtonText: '确定',
        customClass: 'my-custom-message-box', // 自定义类名
      });
      return;
    }
    if (!projectImage.value) {
      showDialog.value = false; // 隐藏弹窗
      ElMessageBox.alert('请输入镜像名', '错误', {
        confirmButtonText: '确定',
        customClass: 'my-custom-message-box', // 自定义类名
      });
      return;
    }

    // 如果没有输入项目位置，提示用户
    if (!useDefaultLocation.value && !projectLocation.value) {
      showDialog.value = false; // 隐藏弹窗
      ElMessageBox.alert('请选择项目位置', '错误', {
        confirmButtonText: '确定',
        customClass: 'my-custom-message-box', // 自定义类名
      });
      return;
    }

    const newProjectPath = projectLocation.value + '/' + projectName.value;

    socket.emit('init',{
      "board": projectBoard.value,
      "framework": projectFramework.value,
      "programLanguage": programLanguage.value,
      "env_image":projectImage.value,
      "example_code":projectExamplecode.value,
      "project_dir":newProjectPath,
    });

    socket.on('init', (res) => {
      showDialog.value = false; // 隐藏弹窗
      // 隐藏加载提示
    loadingInstance.value.close();

      if (res.error) {
        console.error(res.error);
      } else {
        socket.emit('is_file', newProjectPath + '/' + 'platformio.ini');
        socket.on('is_file', (res) => {
          if (res) {
            addNewProject(newProjectPath);
            socket.emit('save_state', { storage: store.state.storage });
            socket.on('save_state', (res) => {
              if (res) {
                fetchData();
              }
            });
            ElMessageBox.alert('项目已创建成功！！！','提示',{           
              confirmButtonText: '确定', // 使用自定义样式类名
              customClass: 'my-custom-message-box', // 自定义整体弹窗的样式类名
              callback: () => {
                location.reload();
              }
            });
          }
        });
      }
    });
  }

  // 清空输入框的值
  projectName.value = '';
  projectBoard.value = '';
  projectFramework.value = '';
  programLanguage.value = '';
  projectImage.value = '';
  projectExamplecode.value = 'https://gitee.com/SuperIDE/examplecode.git';
  projectLocation.value = store.state.ProjectsDir;
  useDefaultLocation.value = true;
  isProjectNameValid.value = null;
}
</script>

<template>
  <div class="flex-1 bg-white rounded-xl pl-5 pr-10 pt-1.5 pb-8 mr-4" style="min-width: 520px">
    <div class="font-bold text-xl pl-4 mt-5">创建项目</div>
    <div class="bg-gray-100 mt-2 mb-5 ml-4" style="height: 1px"></div>
    <form @submit.prevent="handleSubmit">
      <div class="flex items-center my-3">
        <div class="w-24 text-right text-gray-600">项目名称：</div>
        <div class="flex-1 relative">
          <el-input class="w-64 " size="large" v-model="projectName" placeholder="请输入项目名称" v-on:blur="checkProjectName" :autofocus="false"/>
          <span v-show="isProjectNameValid===true" class="text-green-600 check-mark absolute -right-5 top-1/2 -translate-y-1/2 font-bold">√</span>
          <span v-show="isProjectNameValid === false" class="text-red-600 check-mark absolute -right-5 top-1/2 -translate-y-1/2 font-bold">✘</span>
        </div>
      </div>
      <div class="flex items-center my-3">
        <div class="w-24 text-right text-gray-600">开发平台：</div>
        <el-select v-model="projectBoard" class="flex-1" placeholder="请选择开发平台" size="large" :disabled="isProjectNameUrl">
          <el-option
            v-for="item in store.state.boardData"
            :key="item.id"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </div>
      <div class="flex items-center my-3">
        <div class="w-24 text-right text-gray-600">编程框架：</div>
        <el-select v-model="projectFramework" class="flex-1" placeholder="请选择编程框架" size="large" :disabled="isProjectNameUrl">
          <el-option
            v-for="framework in selectedBoard.frameworks"
            :key="framework"
            :label="framework"
            :value="framework"
          />
        </el-select>
      </div>
      <div class="flex items-center my-3">
        <div class="w-24 text-right text-gray-600">编程语言：</div>
        <div class="flex-1">
          <el-input size="large" v-model="programLanguage" placeholder="请输入编程语言" :disabled="isProjectNameUrl"/>
        </div>
      </div>
      <div class="flex items-center my-3">
        <div class="w-24 text-right text-gray-600">项目镜像：</div>
        <div class="flex-1">
          <el-input size="large" v-model="projectImage" placeholder="请输入镜像名" :disabled="isProjectNameUrl"/>
        </div>
      </div>
      <div class="flex items-center my-3">
        <div class="w-24 text-right text-gray-600">范例项目：</div>
        <div class="flex-1">
          <el-input size="large" v-model="projectExamplecode" placeholder="请输入指定的url" :disabled="isProjectNameUrl"/>
        </div>
      </div>
      <div class="flex items-center my-3">
        <div class="w-24 text-right text-gray-600">项目位置：</div>
        <div class="flex-1">
          <el-input size="large" v-model="projectLocation" placeholder="请填写项目位置" :disabled="useDefaultLocation"/>
        </div>
      </div>
      <div class="flex justify-between items-center mt-5">
        <div class="flex items-center">
          <el-switch class="mt-0 ml-24" active-color="#409eff" size="" @change="changeDefaultLocation"
                     v-model="useDefaultLocation"
          ></el-switch>
          <div @click="clickChangeTxt" class="ml-2 cursor-pointer select-none">默认位置</div>
        </div>
        <el-button @click="handleSubmit" type="primary" class="hover:opacity-50" style="background: #409eff; border-color: transparent">确认创建</el-button>
      </div>
    </form>

    <!-- 弹窗部分 -->
    <el-dialog title="提示" :visible.sync="showDialog" width="30%">
      <span>项目创建中...</span>
    </el-dialog>
  </div>
</template>
